package com.sys.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class MyCorsConfig {

    @Value("${myapp.web}")
    private String webRoute;

    @Bean
    public CorsFilter corsFilter() {

        // 一、创建配置源对象
        // 1、添加cors配置信息
        CorsConfiguration configuration = new CorsConfiguration();
        // 2、允许指定域名异步访问
        configuration.addAllowedOrigin(webRoute);
        // 3、是否发送cookie信息
        configuration.setAllowCredentials(true);
        // 4、允许的请求方式
        configuration.addAllowedMethod("OPTIONS");
        configuration.addAllowedMethod("HEAD");
        configuration.addAllowedMethod("GET");
        configuration.addAllowedMethod("PUT");
        configuration.addAllowedMethod("POST");
        configuration.addAllowedMethod("DELETE");
        configuration.addAllowedMethod("PATCH");
        // 5、允许的头信息
        configuration.addAllowedHeader("*");

        // 二、过滤器
        // 过滤资源。添加映射路径，这里我们拦截一切请求
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", configuration);

        // 三、返回新的CorsFilter
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
